﻿using System.Xml;
using System.Xml.Serialization;

namespace PLCS.Shared.Common.Helper;

/// <summary>
/// xml帮助类
/// </summary>
public static class XMLHelper
{
    /// <summary>
    /// 将xml转为实体类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static T DeserializeXml<T>(string xmlString)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        XmlReaderSettings settings = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment };

        using (StringReader reader = new StringReader(xmlString))
        using (XmlReader xmlReader = XmlReader.Create(reader, settings))
        {
            return (T)serializer.Deserialize(xmlReader);
        }
    }

    public static string SerializeToXml<T>(T obj)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
        namespaces.Add("", ""); // 添加一个空的命名空间前缀和URI

        using (StringWriter writer = new StringWriter())
        {
            using (XmlWriter xmlWriter = XmlWriter.Create(writer, new XmlWriterSettings { OmitXmlDeclaration = true }))
            {
                serializer.Serialize(xmlWriter, obj, namespaces);
                return writer.ToString();
            }
        }
    }
}